package com.chnbst.bstyun.controller.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.alipay.util.UtilDate;
import com.chinapay.util.ConsumeFinance;
import com.chinapay.util.ConsumeFinance.Currency;
import com.chinapay.util.CreatePayHtml;
import com.chnbst.bstyun.core.common.BankpayConfig;
import com.chnbst.bstyun.core.common.CreateOrderNum;
import com.chnbst.bstyun.eos.CreateNum;
import com.chnbst.bstyun.eos.Eos;
import com.chnbst.bstyun.model.pojo.Cashflow;
import com.chnbst.bstyun.model.pojo.Deal;
import com.chnbst.bstyun.model.pojo.Goods;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.Supplier;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.pojo.Voucher;
import com.chnbst.bstyun.service.CashflowService;
import com.chnbst.bstyun.service.DealService;
import com.chnbst.bstyun.service.GoodsService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.SupplierService;
import com.chnbst.bstyun.service.UserService;
import com.chnbst.bstyun.service.VoucherService;

/**
 * 银联支付相关
 * @author zqh
 * @date 2014年10月11日
 * 
 */
@Controller
@RequestMapping("/chinapay")
@SessionAttributes(value={"order","payWayName","EOSresult"})
public class ChinaPayController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private DealService dealService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private VoucherService voucherService;
	@Autowired
	private CashflowService cashflowService;
	@Autowired 
	private Eos eos;
	@Autowired 
	private CreateNum createNum;
	@Autowired
	private BankpayConfig bankpayConfig;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private GoodsService goodsService;
	
	private static final String ROLE_AGENT = "ROLE_AGENT";//代理商
	
	Currency currency=Currency.CHINARMB;
	
	DecimalFormat decimalFormat = new DecimalFormat("#0.00");
	
	/**
	 * B2B支付方式（购买产品）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/payByB2B")
	public @ResponseBody String payByB2B(HttpServletRequest request,HttpServletResponse response){
		// 代金券编号
		String voucher = request.getParameter("voucher");
		// 用户id
		String userId = request.getParameter("userId");
		// 用户账户余额支付金额
		String accountMoney = request.getParameter("payByAccountMoney");
		String orderId = request.getParameter("orderId");

		double voucherMoney = 0.00;
		if(!"0".equals(voucher)) {
			voucherMoney = voucherService.selectVoucherByVoucherNum(voucher).getVoucherMoney();
		}
		Order order = orderService.selectOrderByOrderId(Integer.valueOf(orderId));
		
		double payByAccountMoney = Double.valueOf(accountMoney);
		if(payByAccountMoney < 0) {
			payByAccountMoney = 0.00;
		}
		
		// 商户私有域，长度不能超过60,不能有特殊符号和汉字
		String Priv1 = userId+","+payByAccountMoney+","+voucher+","+orderId;
		
		// 商户号B2B
		String MerId = "808080201304755";
		// 订单号
		String OrdId = request.getParameter("orderNum");
		
		/**
		 * 根据用户的roleId 来查询是否为代理商，如果是代理商，查询出优惠折扣等放入session
		 */
		
		DecimalFormat df = new DecimalFormat("#0.00");
		String mealPrivilege = "1";
		String proPrivilege = "1";
		
		User loginUser = userService.selectUserInfoByUserId(Integer.valueOf(userId));
		if(loginUser.getRoleId().equals(ROLE_AGENT) && loginUser.getSupplierId() != null){
			Supplier supplierInfo = supplierService.selectSupplierBySupplierId(loginUser.getSupplierId());
			if(supplierInfo.getIsValid() == 1){
				mealPrivilege = df.format(supplierInfo.getMealPrivilege());
				proPrivilege = df.format(supplierInfo.getProPrivilege());
			}
		}
		double orderMoney = order.getOrderMoney();
		
		Goods goods = goodsService.selectGoodsVoByGoodsId(order.getGoodsId());
		if("0".equals(goods.getGoodsRalateGoods())){
			orderMoney = orderMoney * Double.valueOf(mealPrivilege);
		}else{
			orderMoney = orderMoney * Double.valueOf(proPrivilege);
		}
		
		//订单支付金额
		String money = String.valueOf(df.format(orderMoney-voucherMoney-payByAccountMoney));
		// 把交易金额转化为16位以分为单位的格式
		Currency currency=Currency.CHINARMB;
		String TransAmt=ConsumeFinance.ConsumeProcess(money, currency);
		// 交易日期，长度为8个字节的数字串，表示格式为：YYYYMMDD。 
		String TransDate = UtilDate.getDate();
		chinapay.PrivateKey prikey1 = new chinapay.PrivateKey();
		chinapay.SecureLink t;
		String path= request.getRealPath("/chinapaykeys/privatekeys/MerPrK_808080201304755_20141010110329.key");
		boolean flag;
		flag=prikey1.buildKey(MerId,0,path); 
		//注意要用哪一个商户号签名就要用对应的key文件。
		if (flag==false) 
		{
		    System.out.println("build key error!");
		    return null;
		}
		t = new chinapay.SecureLink(prikey1);
		StringBuilder builder = new StringBuilder(); 
		builder.append(MerId).append(OrdId).append(TransAmt).append(bankpayConfig.getCuryId()).append(TransDate).append(bankpayConfig.getTransType()).append(Priv1);
		String signMsg = builder.toString();
		// 即NetPayClient根据上述输入参数生成的商户数字签名，长度为256字节的字符串
		String CheckValue = t.Sign(signMsg);
		boolean f;
		f = t.verifyAuthToken(signMsg, CheckValue);
		if(f==false){
			System.out.println("签名验证错误！");
			return null;
		}
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("MerId", MerId);
		sParaTemp.put("OrdId", OrdId);
		sParaTemp.put("TransAmt", TransAmt);
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("TransDate", TransDate);
		sParaTemp.put("TransType", bankpayConfig.getTransType());
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("Version", bankpayConfig.getVersion());
		sParaTemp.put("BgRetUrl", bankpayConfig.getBgRetUrl());
		sParaTemp.put("PageRetUrl", bankpayConfig.getPageRetUrl());
		sParaTemp.put("Priv1", Priv1);
		sParaTemp.put("ChkValue", CheckValue);
		//建立请求
		String sHtmlText = CreatePayHtml.buildRequest(sParaTemp);
		return sHtmlText;
	}
	
	/**
	 * B2C支付方式（购买产品）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/payByB2C")
	public @ResponseBody String payByB2C(HttpServletRequest request,HttpServletResponse response){
		// 代金券编号
		String voucher = request.getParameter("voucher");
		// 用户id
		String userId = request.getParameter("userId");
		// 用户账户余额支付金额
		String accountMoney = request.getParameter("payByAccountMoney");
		// 订单id(主键)
		String orderId = request.getParameter("orderId");
		
		double voucherMoney = 0.00;
		if(!"0".equals(voucher)) {
			voucherMoney = voucherService.selectVoucherByVoucherNum(voucher).getVoucherMoney();
		}
		Order order = orderService.selectOrderByOrderId(Integer.valueOf(orderId));
		
		double payByAccountMoney = Double.valueOf(accountMoney);
		if(payByAccountMoney < 0) {
			payByAccountMoney = 0.00;
		}
		
		// 商户私有域，长度不能超过60,不能有特殊符号和汉字
		String Priv1 = userId+","+payByAccountMoney+","+voucher+","+orderId;
		
		// 商户号B2C
		String MerId = "808080201304756";
		// 订单号
		String OrdId = request.getParameter("orderNum");
		
		/**
		 * 根据用户的roleId 来查询是否为代理商，如果是代理商，查询出优惠折扣等放入session
		 */
		
		DecimalFormat df = new DecimalFormat("#0.00");
		String mealPrivilege = "1";
		String proPrivilege = "1";
		
		User loginUser = userService.selectUserInfoByUserId(Integer.valueOf(userId));
		if(loginUser.getRoleId().equals(ROLE_AGENT) && loginUser.getSupplierId() != null){
			Supplier supplierInfo = supplierService.selectSupplierBySupplierId(loginUser.getSupplierId());
			if(supplierInfo.getIsValid() == 1){
				mealPrivilege = df.format(supplierInfo.getMealPrivilege());
				proPrivilege = df.format(supplierInfo.getProPrivilege());
			}
		}
		double orderMoney = order.getOrderMoney();
		
		Goods goods = goodsService.selectGoodsVoByGoodsId(order.getGoodsId());
		if("0".equals(goods.getGoodsRalateGoods())){
			orderMoney = orderMoney * Double.valueOf(mealPrivilege);
		}else{
			orderMoney = orderMoney * Double.valueOf(proPrivilege);
		}
		
		//订单支付金额
		String money = String.valueOf(decimalFormat.format(orderMoney-voucherMoney-payByAccountMoney));
		// 把交易金额转化为16位以分为单位的格式
		Currency currency=Currency.CHINARMB;
		String TransAmt=ConsumeFinance.ConsumeProcess(money, currency);
		// 交易日期，长度为8个字节的数字串，表示格式为：YYYYMMDD。 
		String TransDate = UtilDate.getDate();
		chinapay.PrivateKey prikey1 = new chinapay.PrivateKey();
		chinapay.SecureLink t;
		String path= request.getRealPath("/chinapaykeys/privatekeys/MerPrK_808080201304756_20141010111032.key");
		boolean flag;
		flag=prikey1.buildKey(MerId,0,path); 
		//注意要用哪一个商户号签名就要用对应的key文件。
		if (flag==false) 
		{
		    System.out.println("build key error!");
		    return null;
		}
		t = new chinapay.SecureLink(prikey1);
		StringBuilder builder = new StringBuilder(); 
		builder.append(MerId).append(OrdId).append(TransAmt).append(bankpayConfig.getCuryId()).append(TransDate).append(bankpayConfig.getTransType()).append(Priv1);
		String signMsg = builder.toString();
		// 即NetPayClient根据上述输入参数生成的商户数字签名，长度为256字节的字符串
		String CheckValue = t.Sign(signMsg);
		boolean f;
		f = t.verifyAuthToken(signMsg, CheckValue);
		if(f==false){
			System.out.println("签名验证错误！");
			return null;
		}
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("MerId", MerId);
		sParaTemp.put("OrdId", OrdId);
		sParaTemp.put("TransAmt", TransAmt);
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("TransDate", TransDate);
		sParaTemp.put("TransType", bankpayConfig.getTransType());
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("Version", bankpayConfig.getVersion());
		sParaTemp.put("BgRetUrl", bankpayConfig.getBgRetUrl());
		sParaTemp.put("PageRetUrl", bankpayConfig.getPageRetUrl());
		sParaTemp.put("Priv1", Priv1);
		sParaTemp.put("ChkValue", CheckValue);
		//建立请求
		String sHtmlText = CreatePayHtml.buildRequest(sParaTemp);
		return sHtmlText;
		
	}
	
	/**
	 * 无卡支付方式(购买产品)
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/payByNoCard")
	public @ResponseBody String payByNoCard(HttpServletRequest request,HttpServletResponse response){
		// 代金券编号
		String voucher = request.getParameter("voucher");
		// 用户id
		String userId = request.getParameter("userId");
		// 用户账户余额支付金额
		String accountMoney = request.getParameter("payByAccountMoney");
		// 订单id(主键)
		String orderId = request.getParameter("orderId");
		
		
		double voucherMoney = 0.00;
		if(!"0".equals(voucher)) {
			voucherMoney = voucherService.selectVoucherByVoucherNum(voucher).getVoucherMoney();
		}
		Order order = orderService.selectOrderByOrderId(Integer.valueOf(orderId));
		
		double payByAccountMoney = Double.valueOf(accountMoney);
		if(payByAccountMoney < 0) {
			payByAccountMoney = 0.00;
		}
		
		// 商户私有域，长度不能超过60,不能有特殊符号和汉字
		String Priv1 = userId+","+payByAccountMoney+","+voucher+","+orderId;
		// 商户号(无卡支付)
		String MerId = "808080201304757";
		// 订单号
		String OrdId = request.getParameter("orderNum");
		
		/**
		 * 根据用户的roleId 来查询是否为代理商，如果是代理商，查询出优惠折扣等放入session
		 */
		
		DecimalFormat df = new DecimalFormat("#0.00");
		String mealPrivilege = "1";
		String proPrivilege = "1";
		
		User loginUser = userService.selectUserInfoByUserId(Integer.valueOf(userId));
		if(loginUser.getRoleId().equals(ROLE_AGENT) && loginUser.getSupplierId() != null){
			Supplier supplierInfo = supplierService.selectSupplierBySupplierId(loginUser.getSupplierId());
			if(supplierInfo.getIsValid() == 1){
				mealPrivilege = df.format(supplierInfo.getMealPrivilege());
				proPrivilege = df.format(supplierInfo.getProPrivilege());
			}
		}
		double orderMoney = order.getOrderMoney();
		
		Goods goods = goodsService.selectGoodsVoByGoodsId(order.getGoodsId());
		if("0".equals(goods.getGoodsRalateGoods())){
			orderMoney = orderMoney * Double.valueOf(mealPrivilege);
		}else{
			orderMoney = orderMoney * Double.valueOf(proPrivilege);
		}
		
		//订单支付金额
		String money = String.valueOf(decimalFormat.format(orderMoney-voucherMoney-payByAccountMoney));
		// 把交易金额转化为16位以分为单位的格式
		Currency currency=Currency.CHINARMB;
		String TransAmt=ConsumeFinance.ConsumeProcess(money, currency);
		// 交易日期，长度为8个字节的数字串，表示格式为：YYYYMMDD。 
		String TransDate = UtilDate.getDate();
		chinapay.PrivateKey prikey1 = new chinapay.PrivateKey();
		chinapay.SecureLink t;
		String path= request.getRealPath("/chinapaykeys/privatekeys/MerPrK_808080201304757_20141010111139.key");
		boolean flag;
		flag=prikey1.buildKey(MerId,0,path); 
		//注意要用哪一个商户号签名就要用对应的key文件。
		if (flag==false) 
		{
		    System.out.println("build key error!");
		    return null;
		}
		t = new chinapay.SecureLink(prikey1);
		StringBuilder builder = new StringBuilder(); 
		builder.append(MerId).append(OrdId).append(TransAmt).append(bankpayConfig.getCuryId()).append(TransDate).append(bankpayConfig.getTransType()).append(Priv1);
		String signMsg = builder.toString();
		// 即NetPayClient根据上述输入参数生成的商户数字签名，长度为256字节的字符串
		String CheckValue = t.Sign(signMsg);
		boolean f;
		f = t.verifyAuthToken(signMsg, CheckValue);
		if(f==false){
			System.out.println("签名验证错误！");
			return null;
		}
		System.out.println(f);
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("MerId", MerId);
		sParaTemp.put("OrdId", OrdId);
		sParaTemp.put("TransAmt", TransAmt);
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("TransDate", TransDate);
		sParaTemp.put("TransType", bankpayConfig.getTransType());
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("Version", bankpayConfig.getVersion());
		sParaTemp.put("BgRetUrl", bankpayConfig.getBgRetUrl());
		sParaTemp.put("PageRetUrl", bankpayConfig.getPageRetUrl());
		sParaTemp.put("Priv1", Priv1);
		sParaTemp.put("ChkValue", CheckValue);
		//建立请求
		String sHtmlText = CreatePayHtml.buildRequest(sParaTemp);
		return sHtmlText;
	}
	
	@RequestMapping("/bgRetUrl")
	public void BgRetUrl(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		PrintWriter out = response.getWriter();
		String  TransDate = null ;
		String  MerId = null ;
		String  OrdId = null ;
		String  TransType = null ;
		String  TransAmt = null ;
		String  CuryId = null ;
		String  ChkValue = null ;
		String  OrderStatus = null ;
		String Priv1 = null;
		try{
			TransDate = request.getParameter("transdate") ;
			MerId = request.getParameter("merid") ;
			OrdId = request.getParameter("orderno");
			TransType = request.getParameter("transtype") ;
			TransAmt = request.getParameter("amount") ;
			CuryId = request.getParameter("currencycode") ;
			OrderStatus	= request.getParameter("status") ;
			ChkValue = request.getParameter("checkvalue") ;
			Priv1 = request.getParameter("Priv1");
			String commons[] = Priv1.split(",");
			String userId = commons[0];
			String payByAccountMoney = commons[1];
			String voucher = commons[2];
			String orderId = commons[3];
			chinapay.PrivateKey key=new chinapay.PrivateKey();
			chinapay.SecureLink t;
			boolean flag;
			boolean flag1;
			String msg="";
			String path= request.getRealPath("/chinapaykeys/publickeys/PgPubk.key");
			flag=key.buildKey("999999999999999",0,path);
			if (flag==false){
				msg="build key error!";
				return;
			}
			t=new chinapay.SecureLink (key);
			flag1=t.verifyTransResponse( MerId,OrdId, TransAmt, CuryId, TransDate, TransType, OrderStatus, ChkValue);
			if (flag1==false){
				System.out.println("交易验证失败!");
				msg="交易验证失败!";
			}else{
				/* …... 数据库更新等相关处理过程 */
		            //验证签名数据通过后，一定要判定交易状态代码是否为"1001"，实现代码请商户自行编写。
				if(OrderStatus =="1001" || OrderStatus.equals("1001")){
					
					// 根据userId获取user所有信息
					User userInfo = userService.selectUserInfoByUserId(Integer.parseInt(userId));
					Double accountMoney = 0.0;
					Double invoiceMoney = 0.0;
					if(!"0.00".equals(payByAccountMoney)){
						accountMoney = userInfo.getAccountMoney()-Double.parseDouble(payByAccountMoney);
						invoiceMoney = userInfo.getInvoiceMoney() + Double.parseDouble(payByAccountMoney);
						//账户余额更新
						userInfo.setAccountMoney(accountMoney);
						userInfo.setInvoiceMoney(invoiceMoney);
						userService.updateUserByKey(userInfo);
					}
					//修改代金券状态
					if(!"0".equals(voucher)){
						Voucher v = voucherService.selectVoucherByVoucherNum(voucher);
						v.setState(1);
						voucherService.updateVoucher(v);
					}
					
					//订单状态修改
					Order order = orderService.selectOrderByOrderId(Integer.parseInt(orderId));
					Goods goods = goodsService.selectGoodsVoByGoodsId(order.getGoodsId());
					order.setVoucherNum(voucher);
					order.setPayByAccount(Double.parseDouble(payByAccountMoney));
					order.setPayByOther(Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
					order.setPayMoney(Double.parseDouble(payByAccountMoney)+Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
					
					/**
					 * 根据用户的roleId 来查询是否为代理商，如果是代理商，查询出优惠折扣计算
					 */
					DecimalFormat df = new DecimalFormat("#0.00");
					String mealPrivilege = "1";
					String proPrivilege = "1";
					
					User loginUser = userService.selectUserInfoByUserId(Integer.valueOf(userId));
					if(loginUser.getRoleId().equals(ROLE_AGENT) && loginUser.getSupplierId() != null){
						Supplier supplierInfo = supplierService.selectSupplierBySupplierId(loginUser.getSupplierId());
						if(supplierInfo.getIsValid() == 1){
							mealPrivilege = df.format(1-supplierInfo.getMealPrivilege());
							proPrivilege = df.format(1-supplierInfo.getProPrivilege());
						}
					}
					double discount = order.getOrderMoney();
					
					if("0".equals(goods.getGoodsRalateGoods())){
						discount = discount * Double.valueOf(mealPrivilege);
					}else{
						discount = discount * Double.valueOf(proPrivilege);
					}
					order.setDiscount(discount);
					order.setOrderState(1);
					order.setPayTime(new Date());
					order.setPayWayId(3);
					orderService.updateOrderByOrderId(order);
					
					//激活新用户
					User user = userService.selectUserInfoByUserId(order.getUserId());
					user.setIsLive("1");
					userService.updateUserByKey(user);
					Deal dealInfo = dealService.selectDealByDealNum(OrdId);
					if(dealInfo == null){
						// 保存交易流水
						Deal deal = new Deal();
						deal.setDealDate(new Date());
						deal.setDealName("银联支付产品");
						deal.setDealNum(OrdId);
						deal.setDealState("2");
						deal.setDisburseMoney(Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
						deal.setIncomeMoney(0.0);
						deal.setPayWayId(3);
						deal.setParentId(userInfo.getUserId());
						deal.setUserId(order.getUserId());
						deal.setIsCancel(0);
						dealService.insertDeal(deal);
						
						//=============================收支明细增加======================================
						//充值记录
						Cashflow cashflow = new Cashflow();
						cashflow.setCashflowNum(createNum.createCashflowNum("2"));
						cashflow.setCreateTime(new Date());
						cashflow.setDealType(1);
						cashflow.setDisburseMoney(0.00);
						cashflow.setIncomeMoney(Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
						cashflow.setOrderId(Integer.parseInt(orderId));
						cashflow.setPayWayId(3);
						cashflow.setThenAccount(userInfo.getAccountMoney() + Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
						cashflow.setUserId(Integer.parseInt(userId));
						cashflow.setIsCancel(0);
						cashflowService.insertCashflow(cashflow);
						
						//交易收支明细
						Cashflow cashflow1 = new Cashflow();
						cashflow1.setCashflowNum(createNum.createCashflowNum("1"));
						cashflow1.setCreateTime(new Date());
						cashflow1.setDealType(2);
						cashflow1.setDisburseMoney(Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
						cashflow1.setIncomeMoney(0.00);
						cashflow1.setOrderId(Integer.parseInt(orderId));
						cashflow1.setPayWayId(3);
						cashflow1.setThenAccount(userInfo.getAccountMoney());
						cashflow1.setUserId(Integer.parseInt(userId));
						cashflow.setIsCancel(0);
						cashflowService.insertCashflow(cashflow1);
						
						//============================================================================
					}
				}
			}
		}catch(Exception e){
			out.println(e.getMessage());
			return;
		}
	}
	
	@RequestMapping("/pageRetUrl")
	public ModelAndView PageRetUrl(HttpServletRequest request,HttpServletResponse response,ModelMap model) throws IOException{
		ModelAndView modelAndView = new ModelAndView();
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String  TransDate = null ;
		String  MerId = null ;
		String  OrdId = null ;
		String  TransType = null ;
		String  TransAmt = null ;
		String  CuryId = null ;
		String  ChkValue = null ;
		String  OrderStatus = null ;
		String Priv1 = null;
		try{
			TransDate = request.getParameter("transdate") ;
			MerId = request.getParameter("merid") ;
			OrdId = request.getParameter("orderno");
			TransType = request.getParameter("transtype") ;
			TransAmt = request.getParameter("amount") ;
			CuryId = request.getParameter("currencycode") ;
			OrderStatus	= request.getParameter("status") ;
			ChkValue = request.getParameter("checkvalue") ;
			Priv1 = request.getParameter("Priv1");
			String commons[] = Priv1.split(",");
			String userId = commons[0];
			String payByAccountMoney = commons[1];
			String voucher = commons[2];
			String orderId = commons[3];
			chinapay.PrivateKey key=new chinapay.PrivateKey();
			chinapay.SecureLink t;
			boolean flag;
			boolean flag1;
			String msg="";
			String path= request.getRealPath("/chinapaykeys/publickeys/PgPubk.key");
			flag=key.buildKey("999999999999999",0,path);
			if (flag==false){
				msg="build key error!";
				return null;
			}
			t=new chinapay.SecureLink (key);
			flag1=t.verifyTransResponse( MerId,OrdId, TransAmt, CuryId, TransDate, TransType, OrderStatus, ChkValue);
			if (flag1==false){
				System.out.println("交易验证失败!");
				msg="交易验证失败!";
			}else{
				/* …... 数据库更新等相关处理过程 */
		            //验证签名数据通过后，一定要判定交易状态代码是否为"1001"，实现代码请商户自行编写。
				if(OrderStatus =="1001" || OrderStatus.equals("1001")){
					Order orderinfo = new Order();
					orderinfo.setOrderNum(OrdId);
					orderinfo.setOrderMoney(Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
					
					String EOSresult = "";
					Order order = orderService.selectOrderByOrderId(Integer.parseInt(orderId));
					Goods goods = goodsService.selectGoodsVoByGoodsId(order.getGoodsId());
					
					if(order.getBuyType() == 0) {
						if("0".equals(goods.getGoodsRalateGoods())){
							//========================普元同步开始<套餐>====================================//
								EOSresult = eos.sendMeal(order);
							//========================普元同步结束<套餐>====================================//
						}else{
							//========================普元同步开始<产品>====================================//
							EOSresult = eos.sendProduct(order);
							//========================普元同步结束<产品>====================================//
						}
					}else {
						EOSresult = eos.sendProOrMeal(order);
					}
					
					if("ok".equals(EOSresult)) {
						order.setIsDredge(1);
						orderService.updateOrderByOrderId(order);
					}
					
					User userMain = userService.selectUserInfoByUserId(Integer.parseInt(userId));
					request.getSession().setAttribute("userInfo", userMain);
					modelAndView.addObject("EOSresult", EOSresult);
					model.addAttribute("EOSresult", EOSresult);
					modelAndView.addObject("payWayName", "银联在线支付");
					modelAndView.addObject("order",orderinfo);
					model.addAttribute("order",orderinfo);
					model.addAttribute("payWayName", "银联在线支付");
					if(order.getBuyType() == 0) {
						modelAndView.setViewName("redirect:/chinapay/order/success");
					}else {
						modelAndView.setViewName("redirect:/chinapay/uporder/success");
					}
				}
			}
		}catch(Exception e){
			out.println(e.getMessage());
		}
		return modelAndView;
	}
	
	// 用户个人账户充值相关支付操作=======================
	
	/**
	 * B2B支付方式（充值）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/rechargeByB2B")
	public @ResponseBody String rechargeByB2B(HttpServletRequest request,HttpServletResponse response){
		// 用户id
		String userId = request.getParameter("userId");
		//代金券编号
		String voucherNum = request.getParameter("voucherNum");
		// 商户私有域，长度不能超过60,不能有特殊符号和汉字
		String Priv1 = userId+","+voucherNum;
		// 商户号B2B
		String MerId = "808080201304755";
		// 订单号
		String OrdId = CreateOrderNum.getOrderNum(Integer.parseInt(userId));
		// 交易金额
		String money = request.getParameter("rechargeNum");
		// 把交易金额转化为16位以分为单位的格式
		Currency currency=Currency.CHINARMB;
		String TransAmt=ConsumeFinance.ConsumeProcess(money, currency);
		// 交易日期，长度为8个字节的数字串，表示格式为：YYYYMMDD。 
		String TransDate = UtilDate.getDate();
		chinapay.PrivateKey prikey1 = new chinapay.PrivateKey();
		chinapay.SecureLink t;
		String path= request.getRealPath("/chinapaykeys/privatekeys/MerPrK_808080201304755_20141010110329.key");
		boolean flag;
		flag=prikey1.buildKey(MerId,0,path); 
		//注意要用哪一个商户号签名就要用对应的key文件。
		if (flag==false) 
		{
		    System.out.println("build key error!");
		    return null;
		}
		t = new chinapay.SecureLink(prikey1);
		StringBuilder builder = new StringBuilder(); 
		builder.append(MerId).append(OrdId).append(TransAmt).append(bankpayConfig.getCuryId()).append(TransDate).append(bankpayConfig.getTransType()).append(Priv1);
		String signMsg = builder.toString();
		// 即NetPayClient根据上述输入参数生成的商户数字签名，长度为256字节的字符串
		String CheckValue = t.Sign(signMsg);
		boolean f;
		f = t.verifyAuthToken(signMsg, CheckValue);
		if(f==false){
			System.out.println("签名验证错误！");
			return null;
		}
		System.out.println(f);
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("MerId", MerId);
		sParaTemp.put("OrdId", OrdId);
		sParaTemp.put("TransAmt", TransAmt);
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("TransDate", TransDate);
		sParaTemp.put("TransType", bankpayConfig.getTransType());
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("Version", bankpayConfig.getVersion());
		sParaTemp.put("BgRetUrl", bankpayConfig.getRechargeBgRetUrl());
		sParaTemp.put("PageRetUrl", bankpayConfig.getRechargePageRetUrl());
		sParaTemp.put("Priv1", Priv1);
		sParaTemp.put("ChkValue", CheckValue);
		//建立请求
		String sHtmlText = CreatePayHtml.buildRequest(sParaTemp);
		return sHtmlText;
	}
	
	/**
	 * B2C支付方式（充值）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/rechargeByB2C")
	public @ResponseBody String rechargeByB2C(HttpServletRequest request,HttpServletResponse response){
		// 用户id
		String userId = request.getParameter("userId");
		//代金券编号
		String voucherNum = request.getParameter("voucherNum");
		// 商户私有域，长度不能超过60,不能有特殊符号和汉字
		String Priv1 = userId+","+voucherNum;
		// 商户号B2C
		String MerId = "808080201304756";
		// 订单号
		String OrdId = CreateOrderNum.getOrderNum(Integer.parseInt(userId));
		// 交易金额
		String money = request.getParameter("rechargeNum");
		// 把交易金额转化为16位以分为单位的格式
		Currency currency=Currency.CHINARMB;
		String TransAmt=ConsumeFinance.ConsumeProcess(money, currency);
		// 交易日期，长度为8个字节的数字串，表示格式为：YYYYMMDD。 
		String TransDate = UtilDate.getDate();
		chinapay.PrivateKey prikey1 = new chinapay.PrivateKey();
		chinapay.SecureLink t;
		String path= request.getRealPath("/chinapaykeys/privatekeys/MerPrK_808080201304756_20141010111032.key");
		boolean flag;
		flag=prikey1.buildKey(MerId,0,path); 
		//注意要用哪一个商户号签名就要用对应的key文件。
		if (flag==false) 
		{
		    System.out.println("build key error!");
		    return null;
		}
		t = new chinapay.SecureLink(prikey1);
		StringBuilder builder = new StringBuilder(); 
		builder.append(MerId).append(OrdId).append(TransAmt).append(bankpayConfig.getCuryId()).append(TransDate).append(bankpayConfig.getTransType()).append(Priv1);
		String signMsg = builder.toString();
		// 即NetPayClient根据上述输入参数生成的商户数字签名，长度为256字节的字符串
		String CheckValue = t.Sign(signMsg);
		boolean f;
		f = t.verifyAuthToken(signMsg, CheckValue);
		if(f==false){
			System.out.println("签名验证错误！");
			return null;
		}
		System.out.println(f);
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("MerId", MerId);
		sParaTemp.put("OrdId", OrdId);
		sParaTemp.put("TransAmt", TransAmt);
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("TransDate", TransDate);
		sParaTemp.put("TransType", bankpayConfig.getTransType());
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("Version", bankpayConfig.getVersion());
		sParaTemp.put("BgRetUrl", bankpayConfig.getRechargeBgRetUrl());
		sParaTemp.put("PageRetUrl", bankpayConfig.getRechargePageRetUrl());
		sParaTemp.put("Priv1", Priv1);
		sParaTemp.put("ChkValue", CheckValue);
		//建立请求
		String sHtmlText = CreatePayHtml.buildRequest(sParaTemp);
		return sHtmlText;
		
	}
	
	
	/**
	 * 无卡支付方式（用户个人账户充值）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/rechargeByNoCard")
	public @ResponseBody String rechargeByNoCard(HttpServletRequest request,HttpServletResponse response){
		// 用户id
		String userId = request.getParameter("userId");
		//代金券编号
		String voucherNum = request.getParameter("voucherNum");
		// 商户私有域，长度不能超过60,不能有特殊符号和汉字
		String Priv1 = userId+","+voucherNum;
		// 商户号(无卡支付)
		String MerId = "808080201304757";
		// 订单号
		String OrdId = CreateOrderNum.getOrderNum(Integer.parseInt(userId));
		// 交易金额
		String money = request.getParameter("rechargeNum");
		// 把交易金额转化为16位以分为单位的格式
		Currency currency=Currency.CHINARMB;
		String TransAmt=ConsumeFinance.ConsumeProcess(money, currency);
		// 交易日期，长度为8个字节的数字串，表示格式为：YYYYMMDD。 
		String TransDate = UtilDate.getDate();
		chinapay.PrivateKey prikey1 = new chinapay.PrivateKey();
		chinapay.SecureLink t;
		String path= request.getRealPath("/chinapaykeys/privatekeys/MerPrK_808080201304757_20141010111139.key");
		boolean flag;
		flag=prikey1.buildKey(MerId,0,path); 
		//注意要用哪一个商户号签名就要用对应的key文件。
		if (flag==false) 
		{
		    System.out.println("build key error!");
		    return null;
		}
		t = new chinapay.SecureLink(prikey1);
		StringBuilder builder = new StringBuilder(); 
		builder.append(MerId).append(OrdId).append(TransAmt).append(bankpayConfig.getCuryId()).append(TransDate).append(bankpayConfig.getTransType()).append(Priv1);
		String signMsg = builder.toString();
		// 即NetPayClient根据上述输入参数生成的商户数字签名，长度为256字节的字符串
		String CheckValue = t.Sign(signMsg);
		boolean f;
		f = t.verifyAuthToken(signMsg, CheckValue);
		if(f==false){
			System.out.println("签名验证错误！");
			return null;
		}
		System.out.println(f);
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("MerId", MerId);
		sParaTemp.put("OrdId", OrdId);
		sParaTemp.put("TransAmt", TransAmt);
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("TransDate", TransDate);
		sParaTemp.put("TransType", bankpayConfig.getTransType());
		sParaTemp.put("CuryId", bankpayConfig.getCuryId());
		sParaTemp.put("Version", bankpayConfig.getVersion());
		sParaTemp.put("BgRetUrl", bankpayConfig.getRechargeBgRetUrl());
		sParaTemp.put("PageRetUrl", bankpayConfig.getRechargePageRetUrl());
		sParaTemp.put("Priv1", Priv1);
				
		sParaTemp.put("ChkValue", CheckValue);
		//建立请求
		String sHtmlText = CreatePayHtml.buildRequest(sParaTemp);
		return sHtmlText;
	}
	
	
	@RequestMapping("/rechargeBgRetUrl")
	public void rechargeBgRetUrl(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String  TransDate = null ;
		String  MerId = null ;
		String  OrdId = null ;
		String  TransType = null ;
		String  TransAmt = null ;
		String  CuryId = null ;
		String  ChkValue = null ;
		String  OrderStatus = null ;
		String Priv1 = null;
		try{
			TransDate = request.getParameter("transdate") ;
			MerId = request.getParameter("merid") ;
			OrdId = request.getParameter("orderno");
			TransType = request.getParameter("transtype") ;
			TransAmt = request.getParameter("amount") ;
			CuryId = request.getParameter("currencycode") ;
			OrderStatus	= request.getParameter("status") ;
			ChkValue = request.getParameter("checkvalue") ;
			Priv1 = request.getParameter("Priv1");
			String Priv[] = Priv1.split(",");
			String userId = Priv[0];
			String voucherNum = Priv[1];
			
			chinapay.PrivateKey key=new chinapay.PrivateKey();
			chinapay.SecureLink t;
			boolean flag;
			boolean flag1;
			String msg="";
			String path= request.getRealPath("/chinapaykeys/publickeys/PgPubk.key");
			flag=key.buildKey("999999999999999",0,path);
			if (flag==false){
				msg="build key error!";
				return;
			}
			t=new chinapay.SecureLink (key);
			flag1=t.verifyTransResponse( MerId,OrdId, TransAmt, CuryId, TransDate, TransType, OrderStatus, ChkValue);
			if (flag1==false){
				System.out.println("交易验证失败!");
				msg="交易验证失败!";
			}else{
				/* …... 数据库更新等相关处理过程 */
		            //验证签名数据通过后，一定要判定交易状态代码是否为"1001"，实现代码请商户自行编写。
				if(OrderStatus =="1001" || OrderStatus.equals("1001")){
					
					Double voucherMoney = 0.00;
					if(!"0".equals(voucherNum)) {
						//使用代金券充值部分
						Voucher voucher = voucherService.selectByVoucherNum(voucherNum);
						voucher.setState(1);
						voucherService.updateVoucher(voucher);
						voucherMoney = voucher.getVoucherMoney();
						
						User _userMain = userService.selectUserInfoByUserId(Integer.parseInt(userId));
						_userMain.setAccountMoney(_userMain.getAccountMoney() + voucherMoney);
						userService.updateUserByKey(_userMain);
						
						Cashflow cashflow = new Cashflow();
						cashflow.setCashflowNum(createNum.createCashflowNum("1"));
						cashflow.setCreateTime(new Date());
						cashflow.setDealType(1);
						cashflow.setDisburseMoney(0.00);
						cashflow.setIncomeMoney(voucherMoney);
						cashflow.setOrderId(0);
						cashflow.setPayWayId(2);
						cashflow.setThenAccount(_userMain.getAccountMoney());
						cashflow.setUserId(_userMain.getUserId());
						cashflow.setIsCancel(0);
						cashflowService.insertCashflow(cashflow);
						
					}
					
					//使用第三方充值部分
					User userMain = userService.selectUserInfoByUserId(Integer.parseInt(userId));
					userMain.setAccountMoney(userMain.getAccountMoney() + Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
					boolean b = userService.updateUserByKey(userMain);
					if(b){
						//=============================收支明细增加======================================
						//充值记录
						Cashflow cashflow = new Cashflow();
						cashflow.setCashflowNum(createNum.createCashflowNum("2"));
						cashflow.setCreateTime(new Date());
						cashflow.setDealType(1);
						cashflow.setDisburseMoney(0.00);
						cashflow.setIncomeMoney(Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
						cashflow.setOrderId(0);//充值不存在订单ID
						cashflow.setPayWayId(3);
						cashflow.setThenAccount(userMain.getAccountMoney());
						cashflow.setUserId(Integer.parseInt(userId));
						cashflow.setIsCancel(0);
						cashflowService.insertCashflow(cashflow);
						//============================================================================
						
					}
				
				}
			}
		}catch(Exception e){
			out.println(e.getMessage());
			return;
		}
	}
	
	@RequestMapping(value="/rechargePageRetUrl",method=RequestMethod.POST)
	public ModelAndView rechargePageRetUrl(HttpServletRequest request,HttpServletResponse response,ModelMap map) throws IOException{
		ModelAndView modelAndView = new ModelAndView();
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String  TransDate = null ;
		String  MerId = null ;
		String  OrdId = null ;
		String  TransType = null ;
		String  TransAmt = null ;
		String  CuryId = null ;
		String  ChkValue = null ;
		String  OrderStatus = null ;
		String Priv1 = null;
		try{
			TransDate = request.getParameter("transdate") ;
			MerId = request.getParameter("merid") ;
			OrdId = request.getParameter("orderno");
			TransType = request.getParameter("transtype") ;
			TransAmt = request.getParameter("amount") ;
			CuryId = request.getParameter("currencycode") ;
			OrderStatus	= request.getParameter("status") ;
			ChkValue = request.getParameter("checkvalue") ;
			Priv1 = request.getParameter("Priv1");
			String Priv[] = Priv1.split(",");
			String userId = Priv[0];
			String voucherNum = Priv[1];
			chinapay.PrivateKey key=new chinapay.PrivateKey();
			chinapay.SecureLink t;
			boolean flag;
			boolean flag1;
			String msg="";
			String path= request.getRealPath("/chinapaykeys/publickeys/PgPubk.key");
			flag=key.buildKey("999999999999999",0,path);
			if (flag==false){
				msg="build key error!";
				return null;
			}
			t=new chinapay.SecureLink (key);
			flag1=t.verifyTransResponse( MerId,OrdId, TransAmt, CuryId, TransDate, TransType, OrderStatus, ChkValue);
			if (flag1==false){
				System.out.println("交易验证失败!");
				msg="交易验证失败!";
			}else{
				/* …... 数据库更新等相关处理过程 */
		            //验证签名数据通过后，一定要判定交易状态代码是否为"1001"，实现代码请商户自行编写。
				if(OrderStatus =="1001" || OrderStatus.equals("1001")){
//					User userMain = userService.selectUserInfoByUserId(Integer.parseInt(userId));
//					userMain.setAccountMoney(userMain.getAccountMoney() + Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
//					boolean b = userService.updateUserByKey(userMain);
//					if(b){
//						Deal deal = new Deal();
//						deal.setDealDate(new Date());
//						deal.setDealName("充值");
//						deal.setDealNum(OrdId);
//						deal.setDealState("2");
//						deal.setDisburseMoney(0.0);
//						deal.setIncomeMoney(Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
//						deal.setPayWayId(3);
//						deal.setParentId(userMain.getParentId());
//						deal.setUserId(Integer.parseInt(userId));
//						deal.setIsCancel(0);
//						dealService.insertDeal(deal);
//					}
				}
				Order orderinfo = new Order();
				orderinfo.setOrderNum(OrdId);
				orderinfo.setOrderMoney(Double.parseDouble(ConsumeFinance.ConsumeProcessReturn(TransAmt,currency)));
				modelAndView.addObject("payWayName", "银联在线支付");
				modelAndView.addObject("order",orderinfo);
				map.addAttribute("order",orderinfo);
				User userInfo = userService.selectUserInfoByUserId(Integer.parseInt(userId));
				request.getSession().setAttribute("userInfo", userInfo);
				map.addAttribute("payWayName", "银联在线支付");
				modelAndView.setViewName("redirect:/chinapay/recharge/success");
			}
		}catch(Exception e){
			out.println(e.getMessage());
			return null;
		}
		return modelAndView;
	}
	// 购买成功通知页面
	@RequestMapping("/order/success")
	public String getOrderSuccess(){
		return "buy/success-order";
	}
	
	// 续费或者升级成功通知页面
	@RequestMapping("/uporder/success")
	public String getUpOrderSuccess(){
		return "users/myservice/uporders_success";
	}
	
	// 充值成功通知页面
	@RequestMapping("/recharge/success")
	public String getRechargeSuccess(){
		return "users/finance_manage/my_account/recharge_success";
	}
	
}
